#!/bin/bash
#
# 股票分析后端 - 运维管理脚本
# 用于日常服务管理、监控和维护
#

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
SERVICE_NAME="stock-backend"
APP_DIR="/home/stockapp/stock-backend"
LOG_DIR="/var/log/stock-backend"

# 显示菜单
show_menu() {
    clear
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  股票分析后端 - 运维管理工具${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo "【服务管理】"
    echo "  1) 启动服务"
    echo "  2) 停止服务"
    echo "  3) 重启服务"
    echo "  4) 查看服务状态"
    echo ""
    echo "【日志查看】"
    echo "  5) 查看实时日志"
    echo "  6) 查看错误日志"
    echo "  7) 查看访问日志"
    echo ""
    echo "【系统监控】"
    echo "  8) 查看系统资源"
    echo "  9) 查看进程信息"
    echo " 10) 查看网络连接"
    echo " 11) 健康检查"
    echo ""
    echo "【数据库管理】"
    echo " 12) 备份数据库"
    echo " 13) 查看数据库状态"
    echo " 14) 清理旧数据"
    echo ""
    echo "【代码更新】"
    echo " 15) 更新代码"
    echo " 16) 重新安装依赖"
    echo ""
    echo "【其他工具】"
    echo " 17) 清理日志"
    echo " 18) 测试API"
    echo " 19) 查看配置"
    echo ""
    echo "  0) 退出"
    echo ""
    echo -e "${GREEN}========================================${NC}"
}

# 启动服务
start_service() {
    echo -e "${YELLOW}正在启动服务...${NC}"
    sudo systemctl start $SERVICE_NAME
    sleep 2
    sudo systemctl status $SERVICE_NAME --no-pager
}

# 停止服务
stop_service() {
    echo -e "${YELLOW}正在停止服务...${NC}"
    sudo systemctl stop $SERVICE_NAME
    sleep 2
    echo -e "${GREEN}服务已停止${NC}"
}

# 重启服务
restart_service() {
    echo -e "${YELLOW}正在重启服务...${NC}"
    sudo systemctl restart $SERVICE_NAME
    sleep 2
    sudo systemctl status $SERVICE_NAME --no-pager
}

# 查看服务状态
check_status() {
    echo -e "${YELLOW}服务状态：${NC}"
    sudo systemctl status $SERVICE_NAME --no-pager
    echo ""
    echo -e "${YELLOW}进程信息：${NC}"
    ps aux | grep -E "gunicorn|uvicorn" | grep -v grep
}

# 查看实时日志
view_logs() {
    echo -e "${YELLOW}实时日志 (Ctrl+C 退出)：${NC}"
    sudo journalctl -u $SERVICE_NAME -f
}

# 查看错误日志
view_error_logs() {
    echo -e "${YELLOW}最近50条错误日志：${NC}"
    if [ -f "$LOG_DIR/error.log" ]; then
        tail -n 50 $LOG_DIR/error.log
    else
        sudo journalctl -u $SERVICE_NAME -p err -n 50 --no-pager
    fi
}

# 查看访问日志
view_access_logs() {
    echo -e "${YELLOW}最近50条访问日志：${NC}"
    if [ -f "$LOG_DIR/access.log" ]; then
        tail -n 50 $LOG_DIR/access.log
    else
        echo "访问日志文件不存在"
    fi
}

# 查看系统资源
view_resources() {
    echo -e "${YELLOW}系统资源使用情况：${NC}"
    echo ""
    echo -e "${BLUE}CPU和内存：${NC}"
    top -bn1 | head -n 5
    echo ""
    echo -e "${BLUE}磁盘使用：${NC}"
    df -h | grep -E "Filesystem|/$|/home"
    echo ""
    echo -e "${BLUE}内存详情：${NC}"
    free -h
}

# 查看进程信息
view_processes() {
    echo -e "${YELLOW}应用进程信息：${NC}"
    ps aux | grep -E "gunicorn|uvicorn|python" | grep -v grep
    echo ""
    echo -e "${YELLOW}端口监听：${NC}"
    sudo netstat -tulpn | grep -E ":8000|:3306|:6379"
}

# 查看网络连接
view_connections() {
    echo -e "${YELLOW}网络连接统计：${NC}"
    echo ""
    echo -e "${BLUE}当前连接数：${NC}"
    sudo netstat -an | grep :8000 | wc -l
    echo ""
    echo -e "${BLUE}连接详情：${NC}"
    sudo netstat -an | grep :8000 | head -n 20
}

# 健康检查
health_check() {
    echo -e "${YELLOW}执行健康检查...${NC}"
    echo ""
    
    # 检查服务状态
    echo -e "${BLUE}1. 服务状态：${NC}"
    if systemctl is-active --quiet $SERVICE_NAME; then
        echo -e "${GREEN}✓ 服务运行中${NC}"
    else
        echo -e "${RED}✗ 服务未运行${NC}"
    fi
    
    # 检查API响应
    echo -e "${BLUE}2. API响应：${NC}"
    RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/health)
    if [ "$RESPONSE" == "200" ]; then
        echo -e "${GREEN}✓ API响应正常 (200)${NC}"
    else
        echo -e "${RED}✗ API响应异常 ($RESPONSE)${NC}"
    fi
    
    # 检查MySQL
    echo -e "${BLUE}3. MySQL数据库：${NC}"
    if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then
        echo -e "${GREEN}✓ MySQL运行中${NC}"
    else
        echo -e "${RED}✗ MySQL未运行${NC}"
    fi
    
    # 检查Redis
    echo -e "${BLUE}4. Redis缓存：${NC}"
    if systemctl is-active --quiet redis || systemctl is-active --quiet redis-server; then
        echo -e "${GREEN}✓ Redis运行中${NC}"
    else
        echo -e "${RED}✗ Redis未运行${NC}"
    fi
    
    # 检查磁盘空间
    echo -e "${BLUE}5. 磁盘空间：${NC}"
    DISK_USAGE=$(df -h / | tail -n 1 | awk '{print $5}' | sed 's/%//')
    if [ "$DISK_USAGE" -lt 80 ]; then
        echo -e "${GREEN}✓ 磁盘使用率: $DISK_USAGE%${NC}"
    else
        echo -e "${YELLOW}⚠ 磁盘使用率较高: $DISK_USAGE%${NC}"
    fi
    
    # 检查内存
    echo -e "${BLUE}6. 内存使用：${NC}"
    MEM_USAGE=$(free | grep Mem | awk '{printf "%.0f", $3/$2 * 100}')
    if [ "$MEM_USAGE" -lt 90 ]; then
        echo -e "${GREEN}✓ 内存使用率: $MEM_USAGE%${NC}"
    else
        echo -e "${YELLOW}⚠ 内存使用率较高: $MEM_USAGE%${NC}"
    fi
}

# 备份数据库
backup_database() {
    echo -e "${YELLOW}开始备份数据库...${NC}"
    
    BACKUP_DIR="$APP_DIR/backups"
    mkdir -p $BACKUP_DIR
    
    DATE=$(date +%Y%m%d_%H%M%S)
    BACKUP_FILE="$BACKUP_DIR/stock_analysis_$DATE.sql"
    
    # 读取数据库配置
    if [ -f "$APP_DIR/.env" ]; then
        DB_USER=$(grep DB_USER $APP_DIR/.env | cut -d '=' -f2)
        DB_PASSWORD=$(grep DB_PASSWORD $APP_DIR/.env | cut -d '=' -f2)
        DB_NAME=$(grep DB_NAME $APP_DIR/.env | cut -d '=' -f2)
        
        mysqldump -u $DB_USER -p$DB_PASSWORD $DB_NAME > $BACKUP_FILE
        gzip $BACKUP_FILE
        
        echo -e "${GREEN}✓ 备份完成: $BACKUP_FILE.gz${NC}"
        
        # 显示备份大小
        ls -lh $BACKUP_FILE.gz
        
        # 清理30天前的备份
        find $BACKUP_DIR -name "*.sql.gz" -mtime +30 -delete
        echo -e "${YELLOW}已清理30天前的备份文件${NC}"
    else
        echo -e "${RED}找不到配置文件${NC}"
    fi
}

# 查看数据库状态
check_database() {
    echo -e "${YELLOW}数据库状态：${NC}"
    
    if [ -f "$APP_DIR/.env" ]; then
        DB_USER=$(grep DB_USER $APP_DIR/.env | cut -d '=' -f2)
        DB_PASSWORD=$(grep DB_PASSWORD $APP_DIR/.env | cut -d '=' -f2)
        DB_NAME=$(grep DB_NAME $APP_DIR/.env | cut -d '=' -f2)
        
        echo -e "${BLUE}数据库表：${NC}"
        mysql -u $DB_USER -p$DB_PASSWORD $DB_NAME -e "SHOW TABLES;"
        
        echo ""
        echo -e "${BLUE}数据统计：${NC}"
        mysql -u $DB_USER -p$DB_PASSWORD $DB_NAME -e "
            SELECT 'stocks' as table_name, COUNT(*) as count FROM stocks
            UNION ALL
            SELECT 'stock_prices', COUNT(*) FROM stock_prices
            UNION ALL
            SELECT 'trading_signals', COUNT(*) FROM trading_signals
            UNION ALL
            SELECT 'trading_points', COUNT(*) FROM trading_points;
        "
    else
        echo -e "${RED}找不到配置文件${NC}"
    fi
}

# 清理旧数据
clean_old_data() {
    echo -e "${YELLOW}清理旧数据...${NC}"
    read -p "确认删除30天前的价格数据？(y/n): " confirm
    
    if [ "$confirm" == "y" ]; then
        if [ -f "$APP_DIR/.env" ]; then
            DB_USER=$(grep DB_USER $APP_DIR/.env | cut -d '=' -f2)
            DB_PASSWORD=$(grep DB_PASSWORD $APP_DIR/.env | cut -d '=' -f2)
            DB_NAME=$(grep DB_NAME $APP_DIR/.env | cut -d '=' -f2)
            
            mysql -u $DB_USER -p$DB_PASSWORD $DB_NAME -e "
                DELETE FROM stock_prices WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);
            "
            
            echo -e "${GREEN}✓ 旧数据清理完成${NC}"
        fi
    else
        echo "取消操作"
    fi
}

# 更新代码
update_code() {
    echo -e "${YELLOW}更新代码...${NC}"
    
    cd $APP_DIR
    
    # 显示当前版本
    echo -e "${BLUE}当前版本：${NC}"
    git log -1 --oneline
    
    # 拉取更新
    echo ""
    echo -e "${YELLOW}拉取最新代码...${NC}"
    sudo -u stockapp git pull
    
    # 重启服务
    echo ""
    read -p "是否重启服务？(y/n): " restart
    if [ "$restart" == "y" ]; then
        restart_service
    fi
}

# 重新安装依赖
reinstall_deps() {
    echo -e "${YELLOW}重新安装依赖...${NC}"
    
    cd $APP_DIR
    sudo -u stockapp bash << 'EOF'
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
EOF
    
    echo -e "${GREEN}✓ 依赖安装完成${NC}"
    
    # 询问是否重启
    read -p "是否重启服务？(y/n): " restart
    if [ "$restart" == "y" ]; then
        restart_service
    fi
}

# 清理日志
clean_logs() {
    echo -e "${YELLOW}清理日志文件...${NC}"
    
    if [ -d "$LOG_DIR" ]; then
        echo "日志目录大小："
        du -sh $LOG_DIR
        
        read -p "确认清理7天前的日志？(y/n): " confirm
        if [ "$confirm" == "y" ]; then
            find $LOG_DIR -name "*.log" -mtime +7 -delete
            echo -e "${GREEN}✓ 日志清理完成${NC}"
            
            echo "清理后大小："
            du -sh $LOG_DIR
        fi
    fi
    
    # 清理journalctl日志
    echo ""
    read -p "是否清理系统日志（保留最近7天）？(y/n): " clean_journal
    if [ "$clean_journal" == "y" ]; then
        sudo journalctl --vacuum-time=7d
        echo -e "${GREEN}✓ 系统日志清理完成${NC}"
    fi
}

# 测试API
test_api() {
    echo -e "${YELLOW}测试API接口...${NC}"
    echo ""
    
    echo -e "${BLUE}1. 健康检查：${NC}"
    curl -s http://localhost:8000/health | jq '.' 2>/dev/null || curl -s http://localhost:8000/health
    echo ""
    
    echo -e "${BLUE}2. 根路径：${NC}"
    curl -s http://localhost:8000/ | jq '.' 2>/dev/null || curl -s http://localhost:8000/
    echo ""
    
    echo -e "${BLUE}3. 测试股票API（600519 贵州茅台）：${NC}"
    curl -s "http://localhost:8000/api/stock/600519" | jq '.' 2>/dev/null || curl -s "http://localhost:8000/api/stock/600519"
    echo ""
}

# 查看配置
view_config() {
    echo -e "${YELLOW}系统配置信息：${NC}"
    echo ""
    
    echo -e "${BLUE}环境变量（隐藏密码）：${NC}"
    if [ -f "$APP_DIR/.env" ]; then
        cat $APP_DIR/.env | sed 's/PASSWORD=.*/PASSWORD=******/g'
    else
        echo "配置文件不存在"
    fi
    
    echo ""
    echo -e "${BLUE}Python版本：${NC}"
    $APP_DIR/venv/bin/python --version
    
    echo ""
    echo -e "${BLUE}已安装包：${NC}"
    $APP_DIR/venv/bin/pip list | grep -E "fastapi|uvicorn|sqlalchemy|redis|pandas"
}

# 主循环
while true; do
    show_menu
    read -p "请选择操作 [0-19]: " choice
    echo ""
    
    case $choice in
        1) start_service ;;
        2) stop_service ;;
        3) restart_service ;;
        4) check_status ;;
        5) view_logs ;;
        6) view_error_logs ;;
        7) view_access_logs ;;
        8) view_resources ;;
        9) view_processes ;;
        10) view_connections ;;
        11) health_check ;;
        12) backup_database ;;
        13) check_database ;;
        14) clean_old_data ;;
        15) update_code ;;
        16) reinstall_deps ;;
        17) clean_logs ;;
        18) test_api ;;
        19) view_config ;;
        0) 
            echo -e "${GREEN}再见！${NC}"
            exit 0
            ;;
        *)
            echo -e "${RED}无效选项${NC}"
            ;;
    esac
    
    echo ""
    read -p "按Enter键继续..."
done

